//
//  YWNoQrcodeLedgerViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/12/5.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWNoQrcodeLedgerViewController.h"
#import "YWSelectBuildingTableViewController.h"
#import "YWCreateTempMissionTableViewController.h"
#import "YWPostTroubleTableViewController.h"
#import "YWKeepWatchAndInspectRecordViewController.h"
#import "YWNoQrcodeLedgerLocationDetailViewController.h"
#import "YWNoQrcodeEquipmentMaintainRecordDetailViewController.h"
#import "YWAssetsInventoryListTableViewController.h"
#import "YWMatchMissionsViewController.h"
#import "YWKeepWatchMissionManager.h"

#import "MBProgressHUD.h"
#import "DOPDropDownMenu.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "MJRefresh.h"
#import "UIScrollView+EmptyDataSet.h"
#import "BHBPopView.h"

#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWApartment.h"
#import "YWFloor.h"
#import "YWLocation.h"
#import "YWEquipmentManager.h"
#import "YWEquipment.h"
#import "YWMissionManager.h"
#import "YWEquipmentType.h"
#import "YWLoginTool.h"
#import "YWNoQrcodeLocationCellModel.h"
#import "YWInspectionMissionManager.h"
#import "YWMatchMissionsViewController.h"
#import "YWKeepWatchMissionManager.h"
#import "YWNotifyManager.h"
#import "YWNoQrcodeRights.h"
#import "YWFunctionManager.h"
#import "YWFunctionModel.h"

#import "YWNoQrcodeLedgerLocationTableViewCell.h"
#import "YWNoQrcodeLedgerEquipmentTableViewCell.h"
#import "YWLedgerEquipmentTypeCountTableViewCell.h"

@interface YWNoQrcodeLedgerViewController ()<DOPDropDownMenuDataSource,DOPDropDownMenuDelegate,DZNEmptyDataSetDelegate, DZNEmptyDataSetSource,YWSelectBuildingTableViewControllerDelegate>
{
    NSInteger page;
}
@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, strong) DOPDropDownMenu *menu;
@property (nonatomic, strong) NSMutableArray *buildingArray;
@property (nonatomic, strong) NSMutableArray *apartmentArray;
@property (nonatomic, strong) NSMutableArray * floorArray;
@property (nonatomic, strong) NSMutableArray *locationArray;
@property (nonatomic, strong) NSMutableArray *equipmentTypeArray;

//当前显示地址
@property (nonatomic, strong) YWBuilding * currentBuilding;
@property (nonatomic, strong) YWApartment * currentApartment;
@property (nonatomic, strong) YWFloor * currentFloor;
@property (nonatomic, strong) YWLocation * currentLocation;
@property (nonatomic, strong) YWEquipmentType * currentEquipmentType;
@property (nonatomic, strong) YWNoQrcodeLocationCellModel * locationModel;
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, strong) UIButton *headButton;

@property (nonatomic, strong) NSMutableArray *currentDataSource;
@property (nonatomic, strong) NSMutableArray *tableViewDataSource;
@property (nonatomic, strong) NSArray * equipmentTypeCountArray;
@end

@implementation YWNoQrcodeLedgerViewController
- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.title = @"设备台账";
    [self rightBarButton];
    [self initDefaultData];//默认选择第一个位置
    // 创建menu 第一次显示 不会调用点击代理，可以用这个手动调用
    if (_currentDataSource.count) {
        [self.menu selectDefalutIndexPath];
    }
    [self setupNotification];
    [self setupTableView];
    if (self.qrcodeId) {
        //扫码的当前位置
        YWLocation *currentLocation = [[YWLocation alloc] init];
        NSInteger locationId = self.qrcodeId?[[YWEquipmentManager shareManager]locationIdWithQrcodeId:self.qrcodeId]:0;
        YWLocation* location = [[YWBuildingManager shareManager] locationWithId:locationId];
        currentLocation.locationName = location.locationName;
        currentLocation.locationId = locationId;
        _currentLocation = currentLocation;
        _currentBuilding = [[YWBuildingManager shareManager] buildingWithLocationId:locationId];
        //当前位置下的设备类型
        _equipmentTypeArray = [self equipmentTypes];
        //当前位置下的设备类型的设备数量统计
        _equipmentTypeCountArray = [self countArray];
        [_currentDataSource replaceObjectAtIndex:_currentDataSource.count-1 withObject:_equipmentTypeArray];
        page = 1;
        //给model赋值
        [self setUpModel:self.qrcodeId];
    }else if (self.locationId){
        YWLocation* location = [[YWBuildingManager shareManager] locationWithId:self.locationId];
        _currentLocation = location;
        _currentFloor = [[YWBuildingManager shareManager] floorWithId:location.floorId];
        _currentApartment = [[YWBuildingManager shareManager] apartmentWithId:_currentFloor.apartmentId];
        _currentBuilding = [[YWBuildingManager shareManager] buildingWithLocationId:self.locationId];
        //当前位置下的设备类型
        _equipmentTypeArray = [self equipmentTypes];
        //当前位置下的设备类型的设备数量统计
        _equipmentTypeCountArray = [self countArray];
        [_currentDataSource replaceObjectAtIndex:_currentDataSource.count-1 withObject:_equipmentTypeArray];
        page = 1;
        [self refreshMatchMissions];
        [self goSelect];
    }else{
        [self setUpModel:nil];
    }
}

- (void)rightBarButton{
    if (self.locationId) {
        _currentBuilding = [[YWBuildingManager shareManager] buildingWithLocationId:self.locationId];
    }else if (self.qrcodeId){
        NSInteger locationId = self.qrcodeId?[[YWEquipmentManager shareManager]locationIdWithQrcodeId:self.qrcodeId]:0;
        _currentBuilding = [[YWBuildingManager shareManager] buildingWithLocationId:locationId];
    }
    if (_currentBuilding == nil) {
        _currentBuilding = self.buildingArray.count ? self.buildingArray[0] : nil;
    }
    NSString * buttonTitle = _currentBuilding.buildingName;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:buttonTitle style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemEvent:)];
}

- (void)initDefaultData{
    page = 1;
    _currentApartment = self.apartmentArray.count ? self.apartmentArray[0] : nil;
    _currentFloor = self.floorArray.count ? self.floorArray[0] : nil;
    _currentLocation = self.locationArray.count ? self.locationArray[0] : nil;
    _currentEquipmentType = self.equipmentTypeArray.count ? self.equipmentTypeArray[0] : nil;
    if (self.buildingArray.count) {
        _currentDataSource = [NSMutableArray arrayWithObjects:self.apartmentArray,self.floorArray,self.locationArray,self.equipmentTypeArray,nil];
    }
}

- (void)setupTableView{
    page = 1;
    [self.tableView registerClass:[YWNoQrcodeLedgerLocationTableViewCell class] forCellReuseIdentifier:YWNoQrcodeLedgerLocationTableViewCellIdentifier];
    [self.tableView registerClass:[YWNoQrcodeLedgerEquipmentTableViewCell class] forCellReuseIdentifier:YWNoQrcodeLedgerEquipmentTableViewCellIdentifier];
    [self.tableView registerClass:[YWLedgerEquipmentTypeCountTableViewCell class] forCellReuseIdentifier:YWLedgerEquipmentTypeCountTableViewCellIdentifier];
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.sectionFooterHeight = 0.01f;
    self.tableView.tableHeaderView = _menu;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    
}

- (void)setupNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMatchMissions) name:KRefreshInspectionTimeLineNotification object:nil];
    [[YWNotifyManager shareManager] addReflashPatrolLineViewObserver:self selector:@selector(refreshMatchMissions)];
    [[YWNotifyManager shareManager] addMissionFinishedObserver:self selector:@selector(refreshMatchMissions)];
}

- (void)refreshFootor
{
    [self requestData:YWTableViewFreshTypeUp];
}

- (void)requestData:(YWTableViewFreshType)refreshType
{
    if (refreshType == YWTableViewFreshTypeUp) {
        page++;
    }
    YWWeakSelf(weakSelf);
    dispatch_async(dispatch_get_main_queue(), ^{
    [weakSelf.tableView.mj_footer endRefreshing];
        weakSelf.tableViewDataSource = nil;
        [weakSelf.tableView reloadData];
    });
}


#pragma mark --- DOPDropDownMenuDelegate
- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu
{
    return _currentDataSource.count;
}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column
{
    return column<0 ? 0 : [_currentDataSource[column] count];
}

- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (indexPath.column == 0){
        YWApartment *apartment = _currentDataSource[indexPath.column][indexPath.row];
        return apartment.apartmentName;
    }else if (indexPath.column == 1){
        YWFloor *floor = _currentDataSource[indexPath.column][indexPath.row];
        return floor.floorName;
    }else if (indexPath.column == 2){
        YWLocation *location = _currentDataSource[indexPath.column][indexPath.row];
        return location.locationName;
    }else{
        YWEquipmentType * equipmentType = _currentDataSource[indexPath.column][indexPath.row];
        return equipmentType.equipmentTypeName;
    }
}

- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath
{
   BOOL needSelect = NO;
   if (indexPath.column == 0){
       YWApartment *apartment = _currentDataSource[indexPath.column][indexPath.row];
       if (self.currentApartment.apartmentId != apartment.apartmentId) {
           needSelect = YES;
           self.currentApartment = apartment;
           _currentFloor = nil;
           _currentLocation = nil;
           _currentEquipmentType = nil;
           NSMutableArray *floorMut = [NSMutableArray array];
           YWFloor * floor = [[YWFloor alloc] init];
           NSString *floorShowName = [YWLoginTool floorShowName];
           floor.floorName = floorShowName.length? floorShowName:@"楼层";
           [floorMut addObject:floor];
           NSArray *floorArrays = [[YWBuildingManager shareManager] floorWithApartmentId:_currentApartment.apartmentId];
           [floorMut addObjectsFromArray:floorArrays];
           _currentFloor = floorMut[0];
           [_currentDataSource replaceObjectAtIndex:1 withObject:floorMut];
           DOPIndexPath *reloadIndexPath = [DOPIndexPath indexPathWithCol:1 row:0];
           [_menu selectIndexPath:reloadIndexPath];
           reloadIndexPath = [DOPIndexPath indexPathWithCol:2 row:0];
           [_menu selectIndexPath:reloadIndexPath];
       }
   }else if (indexPath.column == 1){
       YWFloor *floor = _currentDataSource[indexPath.column][indexPath.row];
       if (self.currentFloor.floorId != floor.floorId) {
           needSelect = YES;
           self.currentFloor = floor;
           _currentLocation = nil;
           _currentEquipmentType = nil;
           NSMutableArray *locationMut = [NSMutableArray array];
           YWLocation * location = [[YWLocation alloc] init];
           NSString *locationShowName = [YWLoginTool locationShowName];
           location.locationName = locationShowName.length? locationShowName:@"位置";
           [locationMut addObject:location];
           NSArray *locationArrays = [[YWBuildingManager shareManager] locationWithFloorId:_currentFloor.floorId];
           [locationMut addObjectsFromArray:locationArrays];
           [_currentDataSource replaceObjectAtIndex:2 withObject:locationMut];
           DOPIndexPath *reloadIndexPathLocation = [DOPIndexPath indexPathWithCol:2 row:0];
           [_menu selectIndexPath:reloadIndexPathLocation];
       }
   }else if (indexPath.column == 2){
       YWLocation *location = _currentDataSource[indexPath.column][indexPath.row];
       if (self.currentLocation.locationId != location.locationId) {
           needSelect = YES;
           self.currentLocation = location;
           _equipmentTypeArray = nil;
           NSMutableArray *equipmentTypeMut = [NSMutableArray array];
           YWEquipmentType * equipmentType = [[YWEquipmentType alloc] init];
           equipmentType.equipmentTypeName = [NSString stringWithFormat:@"设备类型"];
           [equipmentTypeMut addObject:equipmentType];

           NSArray * typeArray = [[YWEquipmentManager shareManager] equipmentTypesWithLocationId:_currentLocation.locationId orBuildingId:_currentBuilding.buildingId];
           [equipmentTypeMut addObjectsFromArray:typeArray];
           [_currentDataSource replaceObjectAtIndex:3 withObject:equipmentTypeMut];
           DOPIndexPath *reloadIndexPathEquipment = [DOPIndexPath indexPathWithCol:3 row:0];
           [_menu selectIndexPath:reloadIndexPathEquipment];
       }
    }else{
        needSelect = YES;
        YWEquipmentType *equipmentType = _currentDataSource[indexPath.column][indexPath.row];
        _currentEquipmentType = equipmentType?:nil;
    }
    if (needSelect) {
        page=1;
        //这里把二维码置空，是为了匹配任务不再是按照二维码匹配，而是按照位置匹配
        _qrcodeId = nil;
        _locationId = 0;
        [self refreshMatchMissions];
        [self goSelect];
    }
}

#pragma mark - Table view data source
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    //当有地址id的时候，设备类型设备数的cell才会显示出来
//    if (_currentLocation.locationId>0) {
//        if (indexPath.section == 0) {
//            return [tableView fd_heightForCellWithIdentifier:YWNoQrcodeLedgerLocationTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWNoQrcodeLedgerLocationTableViewCell *cell) {
//                cell.locationModel = self.locationModel;
//            }];
//        }else if (indexPath.section == 1) {
//            return self.equipmentTypeCountArray.count?(kGapH+kLabelH)*self.equipmentTypeCountArray.count+kGapH:0;
//        }else{
//            return [tableView fd_heightForCellWithIdentifier:YWNoQrcodeLedgerEquipmentTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWNoQrcodeLedgerEquipmentTableViewCell *cell) {
//                [self configureNoQrcodeEquipmentLedgerCell:cell atIndexPath:indexPath];
//            }];
//        }
//    }else{
//        if (indexPath.section == 0) {
//            return [tableView fd_heightForCellWithIdentifier:YWNoQrcodeLedgerLocationTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWNoQrcodeLedgerLocationTableViewCell *cell) {
//                cell.locationModel = self.locationModel;
//            }];
//        }else{
//            return [tableView fd_heightForCellWithIdentifier:YWNoQrcodeLedgerEquipmentTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWNoQrcodeLedgerEquipmentTableViewCell *cell) {
//                [self configureNoQrcodeEquipmentLedgerCell:cell atIndexPath:indexPath];
//            }];
//        }
//    }
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSInteger dataSourceCount = self.tableViewDataSource.count;
//    NSInteger equTypeCount = self.equipmentTypeCountArray.count;
    if (_currentLocation.locationId>0) {
        //2表示一个cell是显示楼盘地址的cell，另一个是设备类型设备数统计的cell。
        return dataSourceCount > 0 ? dataSourceCount + 2:dataSourceCount + 1;
    }else{
        return dataSourceCount + 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_currentLocation.locationId>0) {
        if (self.tableViewDataSource.count>0) {
            if (section == 0) {
                return 1;
            }else if(section == 1){
                return 1;
            }else{
                return [self.tableViewDataSource[section - 2] count];
            }
        }else{
            if (section == 0) {
                return 1;
            }else{
                return [self.tableViewDataSource[section - 1] count];
            }
        }
    }
    else{
        if (section == 0) {
            return 1;
        }else{
            return [self.tableViewDataSource[section - 1] count];
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_currentLocation.locationId>0) {
        if (indexPath.section == 0) {
            YWNoQrcodeLedgerLocationTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWNoQrcodeLedgerLocationTableViewCellIdentifier];
            //传值
            cell.locationModel = self.locationModel;
            return cell;
        }else if (indexPath.section == 1){
            YWLedgerEquipmentTypeCountTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWLedgerEquipmentTypeCountTableViewCellIdentifier];
            cell.equipmentTypeArray = self.equipmentTypeCountArray;
            return cell;
        }
        else{
            YWNoQrcodeLedgerEquipmentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWNoQrcodeLedgerEquipmentTableViewCellIdentifier];
            [self configureNoQrcodeEquipmentLedgerCell:cell atIndexPath:indexPath];
            return cell;
        }
    }else{
        if (indexPath.section == 0) {
            YWNoQrcodeLedgerLocationTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWNoQrcodeLedgerLocationTableViewCellIdentifier];
            //传值
            cell.locationModel = self.locationModel;
            return cell;
        }
        else{
            YWNoQrcodeLedgerEquipmentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWNoQrcodeLedgerEquipmentTableViewCellIdentifier];
            [self configureNoQrcodeEquipmentLedgerCell:cell atIndexPath:indexPath];
            return cell;
        }
    }
}

- (void)configureNoQrcodeEquipmentLedgerCell:(YWNoQrcodeLedgerEquipmentTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    if (_currentLocation.locationId>0) {
        YWEquipment *equipment = self.tableViewDataSource[indexPath.section-2][indexPath.row];
        cell.equipment = equipment;
    }
    else{
        YWEquipment *equipment = self.tableViewDataSource[indexPath.section-1][indexPath.row];
        cell.equipment = equipment;
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        if (self.matchMissions.count) {
            if (!_headView) {
                _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kButtonH+kTopPadding*3)];
            }
            if (!_headButton) {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
                [button setFrame:CGRectMake(50, kTopPadding*2, SCREEN_WIDTH-100, kButtonH)];
                button.titleLabel.font = kBoldContentFont;
                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                button.clipsToBounds = YES;
                button.layer.cornerRadius = 4.0;
                [button addTarget:self action:@selector(clickHeadViewButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
                _headButton = button;
            }
            [self setUpButton:_headButton];
            
            [_headView addSubview:_headButton];
            return _headView;
        }else{
            [_headButton removeFromSuperview];
            return nil;
        }
    }else{
        static NSString* HeaderIdentifier = @"YWNoQrcodeLedgerViewControllerForHeaderInSection";
        
        UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
        if (headerView == nil) {
            headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
            UILabel* label = [[UILabel alloc] init];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor customTextGrayColor];
            label.tag = 1009;
            label.numberOfLines = 0;
            label.font = KSmallContentFont;
            [headerView addSubview:label];
        }
        NSString *headText = [self tableViewHeadTxt:section];
        UILabel* label = [headerView viewWithTag:1009];
        label.text = headText;
        label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 25);
        return headerView;
    }
}

-(NSString *)tableViewHeadTxt:(NSInteger)section{
    if (_currentLocation.locationId>0) {
        if (section == 1) {
            if (self.equipmentTypeCountArray.count) {
                return @"设备统计";
            }else{
                return @"";
            }
        }else{
            YWEquipment * equipment = self.tableViewDataSource[section-2][0];
            NSString *equipmentTypeName = [[YWEquipmentManager shareManager] equipmentTypeNameWithTypeId:equipment.equipmentTypeId];
//            NSString *count = [NSString stringWithFormat:@"%ld个",(unsigned long)[self.tableViewDataSource[section-2] count]];
            NSInteger count = [[YWEquipmentManager shareManager] equipmentCountWithBuildingId:_currentBuilding.buildingId ApartmentId:_currentApartment.apartmentId floorId:_currentFloor.floorId locationId:_currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:equipment.equipmentTypeId];
            NSString *headText = [NSString stringWithFormat:@"%@  %ld",equipmentTypeName,(long)count];
            return headText;
        }
    }else{
        YWEquipment * equipment = self.tableViewDataSource[section-1][0];
        NSString *equipmentTypeName = [[YWEquipmentManager shareManager] equipmentTypeNameWithTypeId:equipment.equipmentTypeId];
//        NSString *count = [NSString stringWithFormat:@"%ld个",(unsigned long)[self.tableViewDataSource[section-1] count]];
        NSInteger count = [[YWEquipmentManager shareManager] equipmentCountWithBuildingId:_currentBuilding.buildingId ApartmentId:_currentApartment.apartmentId floorId:_currentFloor.floorId locationId:_currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:equipment.equipmentTypeId];
        NSString *headText = [NSString stringWithFormat:@"%@  %ld",equipmentTypeName,(long)count];
        return headText;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        if (self.matchMissions.count) {
            return kButtonH+kTopPadding*3;
        }else{
            return 0;
        }
    }else{
        return 25;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_currentLocation.locationId>0) {
        if (indexPath.section == 0) {
            YWNoQrcodeLedgerLocationDetailViewController * locationDetailVC = [[YWNoQrcodeLedgerLocationDetailViewController alloc] init];
            locationDetailVC.locationId = self.currentLocation.locationId;
            locationDetailVC.qrcodeId = self.qrcodeId;
            [self.navigationController pushViewController:locationDetailVC animated:YES];
        }else if (indexPath.section != 1) {
            YWEquipment *equipment = self.tableViewDataSource[indexPath.section-2][indexPath.row];        YWNoQrcodeEquipmentMaintainRecordDetailViewController * maintainRecondDetailVC = [[YWNoQrcodeEquipmentMaintainRecordDetailViewController alloc] init];
            NSArray* pictures = [[YWMissionManager shareManager] picturesWithEquipmentId:equipment.equipmentId pictureTroubleType:YWPictureTroubleTypeEquipment];
            equipment.pictures = pictures;
            maintainRecondDetailVC.equipment=equipment;
            maintainRecondDetailVC.isScanEnter = self.qrcodeId ? YES : NO;
            [self.navigationController pushViewController:maintainRecondDetailVC animated:YES];
        }
    }
    else{
        if (indexPath.section == 0) {
            UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:@"请先选择方位" preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:[UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:nil]];
            [self presentViewController:alertController animated:YES completion:nil];
        }else if (indexPath.section != 0) {
            YWEquipment *equipment = self.tableViewDataSource[indexPath.section-1][indexPath.row];        YWNoQrcodeEquipmentMaintainRecordDetailViewController * maintainRecondDetailVC = [[YWNoQrcodeEquipmentMaintainRecordDetailViewController alloc] init];
            NSArray* pictures = [[YWMissionManager shareManager] picturesWithEquipmentId:equipment.equipmentId pictureTroubleType:YWPictureTroubleTypeEquipment];
            equipment.pictures = pictures;
            maintainRecondDetailVC.equipment=equipment;
            maintainRecondDetailVC.isScanEnter = self.qrcodeId ? YES : NO;
            [self.navigationController pushViewController:maintainRecondDetailVC animated:YES];
        }
    }
}


#pragma mark----懒加载
- (DOPDropDownMenu *)menu{
    if (!_menu) {
        DOPDropDownMenu *menu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, 64) andHeight:44];
        menu.delegate = self;
        menu.dataSource = self;
        _menu = menu;
    }
    return _menu;
}

- (NSMutableArray *)buildingArray{
    if (!_buildingArray) {
        NSArray *allBuilding = [[YWBuildingManager shareManager] allBuilding];
        _buildingArray = [NSMutableArray array];
        [_buildingArray addObjectsFromArray:allBuilding];
    }
    return _buildingArray;
}

- (NSMutableArray *)apartmentArray{
    if (!_apartmentArray) {
        NSArray *allApartment = [[YWBuildingManager shareManager] apartmentWithbuildingId:self.currentBuilding.buildingId];
        _apartmentArray = [NSMutableArray array];
        YWApartment *apartment = [[YWApartment alloc] init];
        NSString *apartmentShowName = [YWLoginTool apartmentShowName];
        apartment.apartmentName = apartmentShowName.length? apartmentShowName:@"楼栋";
        [_apartmentArray addObject:apartment];
        [_apartmentArray addObjectsFromArray:allApartment];
    }
    return _apartmentArray;
}

- (NSMutableArray *)floorArray{
    if (!_floorArray) {
        NSArray *allFloor = [[YWBuildingManager shareManager] floorWithApartmentId:self.currentApartment.apartmentId];
        _floorArray = [NSMutableArray array];
        YWFloor *floor = [[YWFloor alloc] init];
        NSString *floorShowName = [YWLoginTool floorShowName];
        floor.floorName = floorShowName.length? floorShowName:@"楼层";
        [_floorArray addObject:floor];
        [_floorArray addObjectsFromArray:allFloor];
    }
    return _floorArray;
}

- (NSMutableArray *)locationArray{
    if (!_locationArray) {
        NSArray *allLocation = [[YWBuildingManager shareManager] locationWithFloorId:self.currentFloor.floorId];
        _locationArray = [NSMutableArray array];
        YWLocation *location = [[YWLocation alloc] init];
        NSString *locationShowName = [YWLoginTool locationShowName];
        location.locationName = locationShowName.length? locationShowName:@"位置";
        [_locationArray addObject:location];
        [_locationArray addObjectsFromArray:allLocation];
    }
    return _locationArray;
}

- (NSMutableArray *)tableViewDataSource{
    if (!_tableViewDataSource) {
        _tableViewDataSource = [NSMutableArray array];
        if (self.qrcodeId) {
            NSArray * equipments = [[YWEquipmentManager shareManager] equipmentInNoQrcodeLedgerWithQrcodeId:self.qrcodeId];
             [_tableViewDataSource addObjectsFromArray:equipments];
        }else if (self.locationId>0){
            YWLocation* location = [[YWBuildingManager shareManager] locationWithId:self.locationId];
            _currentLocation = location;
            _currentFloor = [[YWBuildingManager shareManager] floorWithId:location.floorId];
            _currentApartment = [[YWBuildingManager shareManager] apartmentWithId:_currentFloor.apartmentId];
            _currentBuilding = [[YWBuildingManager shareManager] buildingWithLocationId:self.locationId];
            NSArray *equipments = [[YWEquipmentManager shareManager] equipmentArrayWithBuildingId:_currentBuilding.buildingId ApartmentId:_currentApartment.apartmentId floorId:_currentFloor.floorId locationId:_currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:_currentEquipmentType.equipmentTypeId page:page];
            
             [_tableViewDataSource addObjectsFromArray:equipments];
        }else{
            NSArray *equipments = [[YWEquipmentManager shareManager] equipmentArrayWithBuildingId:_currentBuilding.buildingId ApartmentId:_currentApartment.apartmentId floorId:_currentFloor.floorId locationId:_currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:_currentEquipmentType.equipmentTypeId page:page];
            
            [_tableViewDataSource addObjectsFromArray:equipments];
        }
    }
    return _tableViewDataSource;
}

- (NSMutableArray *)equipmentTypeArray{
    if (!_equipmentTypeArray) {
        _equipmentTypeArray = [self equipmentTypes];
    }
    return _equipmentTypeArray;
}

- (NSMutableArray *)equipmentTypes{
    NSMutableArray * equipmentMut = [NSMutableArray array];
    YWEquipmentType * equipmentType = [[YWEquipmentType alloc] init];
    equipmentType.equipmentTypeName = [NSString stringWithFormat:@"设备类型"];
    [equipmentMut addObject:equipmentType];
    
    NSArray * typeArray = [[YWEquipmentManager shareManager] equipmentTypesWithLocationId:_currentLocation.locationId orBuildingId:_currentBuilding.buildingId];
    [equipmentMut addObjectsFromArray:typeArray];
    return equipmentMut;
}

- (NSArray*)equipmentTypeCountArray{
    if (!_equipmentTypeCountArray) {
        _equipmentTypeCountArray = [self countArray];
    }
    return _equipmentTypeCountArray;
}

- (NSArray*)countArray{
    if (self.qrcodeId) {
        NSArray * countArray = [[YWEquipmentManager shareManager] equipmentTypeArrayWithQrcodeId:self.qrcodeId];
        return countArray;
    }else{
        NSArray * countArray = [[YWEquipmentManager shareManager] equipmentTypeArrayWithLocationId:_currentLocation.locationId AndEquipmentTypeId:_currentEquipmentType.equipmentTypeId];
        return countArray;
    }
}

- (YWNoQrcodeLocationCellModel*)locationModel{
    if (!_locationModel) {
        //构建model
        YWNoQrcodeLocationCellModel * locationModel = [[YWNoQrcodeLocationCellModel alloc] init];
        _locationModel = locationModel;
    }
    return _locationModel;
}


- (void)setUpButton:(UIButton*)button{
    NSInteger count = self.matchMissions.count;
    NSString *countStr = @"";
    if (count > 0) {
        countStr = [NSString stringWithFormat:@"已匹配%lu条待执行的任务",(unsigned long)self.matchMissions.count];
        button.backgroundColor = [UIColor customBlueColor];
    }else{
//        countStr = @"此二维码无待执行的任务";
//        button.backgroundColor = [UIColor customTextGrayBlackColor];
//        self.tableView.tableHeaderView.hidden = YES;
    }
    [button setTitle:countStr forState:UIControlStateNormal];
}

- (void)refreshMatchMissions{
    NSInteger count = [self.matchMissions count];
    if (self.qrcodeId) {
        NSArray *matchMission = [[YWMissionManager shareManager] matchAllTypeMissionsWithQrcodeId:self.qrcodeId];
        self.matchMissions = matchMission;
        [self setUpButton:self.headButton];
    }else{
        if (self.currentLocation.locationId) {
            NSArray *matchMission = [[YWMissionManager shareManager] matchAllTypeMissionsWithLocationId:self.currentLocation.locationId];
            self.matchMissions = matchMission;
            [self setUpButton:self.headButton];
        }else{
            self.matchMissions = nil;
        }
    }
    if (self.matchMissions.count==0 && _headButton) {
        [_headButton removeFromSuperview];
        if (count>0) {
            [self.tableView reloadData];
        }
    }
}

- (void)clickHeadViewButtonEvent:(id)sender{
    //点击headView,跳转匹配的任务列表
    if (self.matchMissions.count>0) {
        YWMatchMissionsViewController *matchMissionVC = [[YWMatchMissionsViewController alloc] init];
        matchMissionVC.matchMissions = self.matchMissions;
        matchMissionVC.qrCodeId = self.qrcodeId;
        matchMissionVC.locationId = self.currentLocation.locationId;
        [self.navigationController pushViewController:matchMissionVC animated:YES];
    }else{
        [YWCommonTool showTextHUDWithContent:@"此二维码无待执行的任务"];
    }
}

- (void)goSelect{
    [self.tableViewDataSource removeAllObjects];
    //给model赋值
    [self setUpModel:nil];
    
    //数据源
    NSArray *equipments = [[YWEquipmentManager shareManager] equipmentArrayWithBuildingId:_currentBuilding.buildingId ApartmentId:_currentApartment.apartmentId floorId:_currentFloor.floorId locationId:_currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:_currentEquipmentType.equipmentTypeId page:page];
    
//    [equipmentMut enumerateObjectsUsingBlock:^(NSArray*  _Nonnull equipmentArray, NSUInteger idx, BOOL * _Nonnull stop) {
//        [equipmentArray enumerateObjectsUsingBlock:^(YWEquipment* _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
//            NSArray* pictures = [[YWMissionManager shareManager] picturesWithEquipmentId:equipment.equipmentId pictureTroubleType:YWPictureTroubleTypeEquipment];
//            equipment.pictures = pictures;
//        }];
//    }];
    
    [self.tableViewDataSource addObjectsFromArray:equipments];
    self.equipmentTypeCountArray = nil;
    
    [self.tableView reloadData];
}
- (void)setUpModel:(NSString*)qrCodeId{
    self.locationModel.apartment = self.currentApartment;
    self.locationModel.floor = self.currentFloor;
    self.locationModel.location = self.currentLocation;
    self.locationModel.building = self.currentBuilding;
    NSInteger equipmentCount = 0;
    if (qrCodeId) {
        equipmentCount = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:self.qrcodeId].count;
    }else{
        equipmentCount = [[YWEquipmentManager shareManager] equipmentCountWithBuildingId:_currentBuilding.buildingId ApartmentId:_currentApartment.apartmentId floorId:_currentFloor.floorId locationId:_currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:_currentEquipmentType.equipmentTypeId];
    }
    self.locationModel.equipmentCount = equipmentCount;
    
    NSInteger qrcodeCount = [[YWEquipmentManager shareManager] qrcodeCountWithBuildingId:_currentBuilding.buildingId ApartmentId:_currentApartment.apartmentId floorId:_currentFloor.floorId locationId:_currentLocation.locationId eqipmentSubSystemType:0 equipmentTypeId:_currentEquipmentType.equipmentTypeId];
    self.locationModel.qrcodeEquipments = qrcodeCount;
}

- (void)rightBarButtonItemEvent:(id)sender{
    //选择楼盘
    YWSelectBuildingTableViewController *selectBuildingVC = [[YWSelectBuildingTableViewController alloc] init];
    selectBuildingVC.delegate = self;
    selectBuildingVC.ownBuilding = _currentBuilding;
    [self.navigationController pushViewController:selectBuildingVC animated:YES];
}

#pragma mark - YWSelectBuildingTableViewControllerDelegate
-(void)popSelectedBuilding:(YWBuilding *)building{
    if (building && ![self.currentBuilding.buildingId isEqualToString:building.buildingId]) {
        //将选中的楼盘赋给当前楼盘，楼栋、楼层、位置等全部置空
        self.currentBuilding = building;
        _currentApartment = nil;
        _currentFloor = nil;
        _currentLocation = nil;
        _currentEquipmentType = nil;
        self.apartmentArray = nil;
        self.floorArray = nil;
        self.locationArray = nil;
        self.equipmentTypeArray = nil;
        self.equipmentTypeCountArray = nil;
        self.qrcodeId = nil;
        [self.navigationItem.rightBarButtonItem setTitle:_currentBuilding.buildingName];
        [self initDefaultData];
        [self goSelect];
        [self refreshMatchMissions];
        [self.menu reloadData];
        [self.tableView reloadData];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = @"查询中";
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
